import { modifyPassword } from '@/services/Detail';
import { removeToken } from '@/utils/auth';
import { history } from '@umijs/max';
import { Button, Drawer, Form, Input, message } from 'antd';
import { stringify } from 'querystring';
interface BindChannelgProps {
  open: boolean;
  onClose: (itemDetail: any) => void;
}

const PopupRight = (props: BindChannelgProps) => {
  const { open, onClose } = props;
  const loginOut = () => {
    const { search, pathname } = window.location;
    const urlParams = new URL(window.location.href).searchParams;
    /** 此方法会跳转到 redirect 参数所在的位置 */
    const redirect = urlParams.get('redirect');
    removeToken();
    // Note: There may be security issues, please note
    if (window.location.pathname !== '/login' && !redirect) {
      history.replace({
        pathname: '/login',
        search: stringify({
          redirect: pathname + search,
        }),
      });
    }
  };
  const onFinish = async (values: any) => {
    if (values.password !== values.repeatPassword)
      return message.error('两次密码不一致');
    modifyPassword(values).then((res) => {
      if (res) {
        message.success('修改成功');
        onClose(true);
        loginOut();
      }
    });
  };
  return (
    <Drawer
      title="修改密码"
      placement="right"
      closable={false}
      onClose={() => onClose(false)}
      open={open}
      width="40%"
      getContainer={false}
    >
      <Form onFinish={onFinish} labelCol={{ span: 5 }}>
        <Form.Item<any>
          label="旧密码"
          rules={[{ required: true, message: '旧密码' }]}
          name="oldPassword"
        >
          <Input.Password type="text" placeholder="旧密码" />
        </Form.Item>
        <Form.Item<any>
          label="新密码"
          rules={[{ required: true, message: '新密码' }]}
          name="password"
        >
          <Input.Password type="text" placeholder="新密码" />
        </Form.Item>
        <Form.Item<any>
          label="确认密码"
          rules={[{ required: true, message: '确认密码' }]}
          name="repeatPassword"
        >
          <Input.Password type="text" placeholder="确认密码" />
        </Form.Item>

        <div style={{ height: '50px' }}>
          <div
            style={{
              height: '50px',
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              display: 'flex',
              alignItems: 'center',
              padding: '0 20px',
              borderTop: '1px solid #e8e8e8',
            }}
          >
            <Button type="primary" ghost={true} onClick={() => onClose(false)}>
              取消
            </Button>
            <Button
              type="primary"
              htmlType="submit"
              style={{ marginLeft: '10px' }}
            >
              确认
            </Button>
          </div>
        </div>
      </Form>
    </Drawer>
  );
};

export default PopupRight;
